package com.voicechat.firstmet.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.PersonalHomepageActivity;
import com.voicechat.firstmet.activity.PostDetailsActivity;
import com.voicechat.firstmet.adapter.CommunityAdapter;
import com.voicechat.firstmet.adapter.FansAndFocusAdapter;
import com.voicechat.firstmet.base.BaseFragment;
import com.voicechat.firstmet.bean.CommBean;
import com.voicechat.firstmet.bean.CoummunityNotice;
import com.voicechat.firstmet.bean.FansAndLike;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.PostBean;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.CommunityService;
import com.voicechat.firstmet.net.service.MeInfoService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.fragment_shar_girls
 * @ClassName: SearchFragment
 * @Description: java类作用描述
 * @Author: ljp
 * @CreateDate: 2018/11/16 10:08
 * @Version: 1.0
 */
public class SearchFragment extends BaseFragment {
    @BindView(R.id.recy_search)
    RecyclerView recySearch;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    Unbinder unbinder;
    private String flag;//判断是用户还是帖子
    private String search;//搜索条件
    private FansAndFocusAdapter fansAndFocusAdapter;
    private ArrayList<FansAndLike.PageBean.ListBean> listBeans;
    private List<PostBean.PageBean.ListBean> postBeans;
    private CommunityAdapter communityAdapter;
    private int page;
    private String token;
    private String deviceInfo;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String userId;
    private String TAG = "SearchFragment";

    public static SearchFragment newInstance(String flag,String search) {
        Bundle args = new Bundle();
        args.putString("flag", flag);
        args.putString("search", search);
        SearchFragment fragment = new SearchFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static SearchFragment newInstance() {
        SearchFragment fragment = new SearchFragment();
        return fragment;
    }

    @Override
    protected int loadLayout() {
        return R.layout.fragment_search;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        userId = mySeleInfo.getId();
        flag = getArguments().getString("flag");
        search = getArguments().getString("search");
        initView();

    }
    /**
     * @return
     * @method
     * @description 数据控件实例化
     * @date: 2018/11/16 10:15
     * @author: ljp
     */
    private void initView() {
        page = 1;
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                if(flag.equals("user")){
                    httpSearchUser();
                }else {
                    httpSearchPost();
                }
                smartRefresh.finishRefresh(10000);
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                if(flag.equals("user")){
                    httpSearchUser();
                }else {
                    httpSearchPost();
                }
                smartRefresh.finishLoadMore(10000);
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        if (flag.equals("user")) {//查看搜索用户
            listBeans = new ArrayList<>();
            fansAndFocusAdapter = new FansAndFocusAdapter(context, listBeans, R.layout.item_fans_focus,"");
            recySearch.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
            recySearch.setAdapter(fansAndFocusAdapter);
            fansAndFocusAdapter.setItemOnClick(new FansAndFocusAdapter.ItemOnClick() {
                @Override
                public void setItemOnClick(int position, View view) {//跳往个人主页
                }
                @Override
                public void setStateOnClick(int position, View view) {//状态点击事件
                    FansAndLike.PageBean.ListBean listBean = listBeans.get(position);
                    setHttpLike(listBean);
                }
                @Override
                public void setIconOnClick(String userId, View view) {
                    Intent intent = new Intent(activity,PersonalHomepageActivity.class);
                    intent.putExtra("anchorId",userId);
                    startActivity(intent);
                }
            });
            if(!TextUtils.isEmpty(search)){
                httpSearchUser();
            }
        } else {//查看搜索帖子
            postBeans = new ArrayList<>();
            communityAdapter = new CommunityAdapter(context, postBeans, R.layout.item1_community, "person");
            recySearch.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
            recySearch.setAdapter(communityAdapter);
            communityAdapter.setItemSetClick(new CommunityAdapter.ItemSetClick() {
                @Override
                public void setIconClick(View view, PostBean.PageBean.ListBean listBean) {
                    Intent intent = new Intent(activity,PersonalHomepageActivity.class);
                    intent.putExtra("anchorId",listBean.getUserId());
                    startActivity(intent);
                }
                @Override
                public void setIconClick(View view, CommBean.MapBean.DynamicBean dynamic) {
                }
                @Override
                public void setItemClick(View view, PostBean.PageBean.ListBean listBean) {
                    Intent intent = new Intent(context,PostDetailsActivity.class);
                    intent.putExtra("listBean",listBean);
                    startActivity(intent);
                }
                @Override
                public void setLikeClick(View view, CommBean.MapBean.DynamicBean dynamic) {
                }
                @Override
                public void setLikeClick(View view, PostBean.PageBean.ListBean listBean) {
                    CommunityService.postLikeAndUnLike(token,deviceInfo,listBean.getId(),
                            CommunityService.LIKE_TYPE.LIKE_POST_TYPE,userId).subscribe(result -> {
                        if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                            if(listBean.getIsFabulous().equals("0")){//0未点赞 1 点赞
                                listBean.setIsFabulous("1");
                                listBean.setFabulousCount(listBean.getFabulousCount()+1);
                            }else if(listBean.getIsFabulous().equals("1")){
                                listBean.setIsFabulous("0");
                                listBean.setFabulousCount(listBean.getFabulousCount()-1);
                            }
                            communityAdapter.notifyDataSetChanged();
                        }else if(result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                            Utils.setToken(context);
                        }else {
                            toast_MakeText(result.getMsg());
                        }
                        // Log.i(TAG, "setLikeClick: -------"+result.toString());
                    },throwable -> {
                        // Log.i(TAG, "setLikeClick: -------"+throwable.toString());
                    });
                }
                @Override
                public void setItemClick(View view, CommBean.MapBean.DynamicBean dynamic) {

                }

                @Override
                public void setNoticeClick(View view, List<CoummunityNotice.PageBean.ListBean> notices) {

                }

                @Override
                public void setPlayVoiceClick(PostBean.PageBean.ListBean listBean, View view, int position, View viewPlay) {

                }


                @Override
                public void setPlayVoiceClick(CommBean.MapBean.DynamicBean dynamic, View view, int position) {

                }

                @Override
                public void setItemClickShare(View view, PostBean.PageBean.ListBean listBean) {
                    UMWeb web = new UMWeb(HTTPAPI.URL_SHARE+"id="+listBean.getId()+"&userId="+listBean.getUserId());
                    String[] list = getResources().getStringArray(R.array.share_title);
                    Random random = new Random();
                    web.setTitle(list[random.nextInt(list.length)]);//标题
                    if (!TextUtils.isEmpty(listBean.getUrl())) {
                        String[] strings = Utils.spitPictureUrl(listBean.getUrl());
                        web.setThumb(new UMImage(activity, OssConfig.OSS_HTTP+strings[0]));  //缩略图
                    }
                    web.setDescription(listBean.getContent());//描述
                    new ShareAction(activity).withMedia(web)
                            .setDisplayList(SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN,SHARE_MEDIA.QZONE,SHARE_MEDIA.WEIXIN_CIRCLE)
                            .setCallback(new UMShareListener() {
                                @Override
                                public void onStart(SHARE_MEDIA share_media) {
                                }
                                @Override
                                public void onResult(SHARE_MEDIA share_media) {
                                    Toast.makeText(activity,getResources().getString(R.string.share_success),Toast.LENGTH_LONG).show();
                                }
                                @Override
                                public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                    Toast.makeText(activity,getResources().getString(R.string.share_fial),Toast.LENGTH_LONG).show();
                                }
                                @Override
                                public void onCancel(SHARE_MEDIA share_media) {
                                    Toast.makeText(activity,getResources().getString(R.string.share_cacal),Toast.LENGTH_LONG).show();
                                }
                            }).open();
                }

            });
            if(!TextUtils.isEmpty(search)){
                httpSearchPost();
            }
        }
    }
    /**
     * @return
     * @method
     * @description 关注取消关注
     * @date: 2018/10/24 11:56
     * @author: ljp
     */
    private void setHttpLike(FansAndLike.PageBean.ListBean listBean) {
        MeInfoService.likeAndUnLike(token, deviceInfo, userId, listBean.getUserId()).subscribe(result -> {
            Log.i(TAG, "setHttpLike: --------" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                if (listBean.getState().equals("1")) {//1 未关注 2已经关注 3互相关注
                    //if (flag.equals("0")) {//我关注列表
                        listBean.setState("2");
                   // } else {//我的粉丝列表
                     //   listBean.setState("3");
                   // }
                } else if (listBean.getState().equals("2")) {
                    listBean.setState("1");
                } else if (listBean.getState().equals("3")) {
                    listBean.setState("1");
                }
                fansAndFocusAdapter.notifyDataSetChanged();
                toast_MakeText(result.getMsg());
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
            Log.i(TAG, "setHttpLike: ------" + throwable.toString());

        });

    }
    /**
    * @method
    * @description 请求搜索帖子数据
    * @date: 2018/11/16 10:22
    * @author: ljp
    * @return
    */
    private void httpSearchPost() {
        MeInfoService.searchPost(userId,token,deviceInfo,search,page+"").subscribe(postBean -> {
            if(postBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){
                int i =  postBean.getPage().getCount() / postBean.getPage().getPageSize() +
                        (postBean.getPage().getCount() % postBean.getPage().getPageSize()==0? 0 : 1 ) ;
                if (page > i ) {//判断是否是最后一页{//判断是否是最后一页
                   // smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                    //Log.i(TAG, "communityPostList: -------------postLists.size();--------" + postLists.size());
                } else {
                    if (page == 1) {
                        postBeans.clear();
                      //  smartRefresh.finishRefresh();
                    }
                    if(postBean.getPage().getCount() != 0){
                        postBeans.addAll(postBean.getPage().getList());
                        communityAdapter.notifyDataSetChanged();
                    }
                    //smartRefresh.finishLoadMore();
                }
            }else if(postBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            }else {
                toast_MakeText(postBean.getMsg());
            }
        },throwable -> {
            Log.i(TAG, "httpSearchPost: -----"+throwable.toString());
            toast_MakeText(getResources().getString(R.string.net_error));
        });

    }

    /**
    * @method
    * @description 搜索用户
    * @date: 2018/11/16 10:18
    * @author: ljp
    * @return
    */
    private void httpSearchUser() {
        MeInfoService.searchUser(userId,token,deviceInfo,search,page+"").subscribe(fansAndLike -> {
            Log.i(TAG, "httpList: ---------"+fansAndLike.getPage().getCount());
            if (fansAndLike.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                int i =  fansAndLike.getPage().getCount() / fansAndLike.getPage().getPageSize() +
                        (fansAndLike.getPage().getCount() % fansAndLike.getPage().getPageSize()==0? 0 : 1 ) ;
                //int i = postBean.getPage().getCount() % postBean.getPage().getPageSize();
                if (i != 0 && page > i ) {//判断是否是最后一页
                   // smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                    // Log.i(TAG, "communityPostList: -------------postLists.size();--------" + postLists.size());
                } else {
                    if (page == 1) {
                        listBeans.clear();
                      //  smartRefresh.finishRefresh();
                    }
                    if(fansAndLike.getPage().getCount() != 0){
                        listBeans.addAll(fansAndLike.getPage().getList());
                        fansAndFocusAdapter.notifyDataSetChanged();
                    }
                  //  smartRefresh.finishLoadMore();
                }
            }else if(fansAndLike.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            }else {
                toast_MakeText(fansAndLike.getMsg());
            }
        },throwable -> {
            Log.i(TAG, "httpSearchUser: -----"+throwable.toString());
            toast_MakeText(getResources().getString(R.string.net_error));
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment_shar_girls view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
